package com.limetalks.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import com.limetalks.data.User;

public class UserDAO {
	private EntityManagerFactory emf;
//	private EntityManager em;
//	private Query findAllQuery;
//	private Query findByEmailPasswordQuery;
	
	public UserDAO(EntityManagerFactory emf) {
		this.emf = emf;
	}
	
	public User findById(Integer userId){
		EntityManager em = emf.createEntityManager();
		return em.find(User.class, userId);
	}
	
	public User findByEmailPassword(String email, String password) {
		EntityManager em = emf.createEntityManager();
		
		Query findByEmailPasswordQuery = em.createNamedQuery("findByEmailPassword");
		findByEmailPasswordQuery.setParameter("email", email);
		findByEmailPasswordQuery.setParameter("password", password);
		try {
			return (User)findByEmailPasswordQuery.getSingleResult();
		} catch (NoResultException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void save(User user) throws PersistenceException {
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(user);
		em.getTransaction().commit();
	}
}
